<template>
	<view class="dialog-container1">
		<view class="item-box" v-if="message.type === 'TIMTextElem'" @click="handleMessage('copy')">
			<view class="icon icon-fuzhi"></view>
			<view class="opr-text">{{$t('chat.chat_copy')}}</view>
		</view>
		<view class="item-box" v-if="message.type === 'TIMSoundElem'" @click="Voicetotext">
			<view class="icon icon-fuzhi"></view>
			<view class="opr-text">{{$t('chat.chat_trans')}}</view>
		</view>
		<view class="item-box" v-if="message.flow === 'out'" @click="handleMessage('revoke')">
			<view class="icon icon-chehuisekuai"></view>
			<view class="opr-text">{{$t('chat.chat_recall')}}</view>
		</view>
		<view class="item-box" @click="handleMessage('delete')">
			<view class="icon icon-shanchutianchong"></view>
			<view class="opr-text">{{$t('chat.chat_delete')}}</view>
		</view>
		<view class="item-box" v-if="number===message.ID" @click="hideTranslate()">
			<view class="icon icon-yincang"></view>
			<view class="opr-text">{{$t('chat.chat_translate')}}</view>
		</view>
		<view class="item-box" @click="For_ward()">
			<view class="icon icon-duoxuan-04"></view>
			<view class="opr-text">{{$t('chat.chat_mul_choose')}}</view>
		</view>
		<view class="item-box" v-if="message.type !== 'TIMSoundElem'" @click="handleMessage('forward')">
			<view class="icon icon-zhuanfa"></view>
			<view class="opr-text">{{$t('chat.chat_forward')}}</view>
		</view>
		<!-- 回复 -->
		<view class="item-box" @click.stop="handleReply">
			<view class="icon">&#xe7d2;</view>
			<view class="opr-text">{{$t('chat.chat_reply')}}</view>
		</view>
		<view class="item-box" v-if="message.flow === 'out' && message.status==='fail'"
			@click="handleMessage('resend')">
			<view class="icon icon-bianji"></view>
			<view class="opr-text">重发</view>
		</view>
		<view class="item-box" @click.stop="Translate(1)" v-if="message.type == 'TIMTextElem'">
			<i class="icon icon-business-translate"></i>
			<text class="opr-text">{{$t('chat.english')}}→{{ $t('chat.chinese')}}</text>
		</view>
		<view class="item-box" @click.stop="Translate(3)" v-if="message.type == 'TIMTextElem'">
			<i class="icon icon-business-translate"></i>
			<text class="opr-text">{{ $t('chat.chinese')}}→{{ $t('chat.english')}}</text>
		</view>
		<view class="item-box" @click.stop="Translate(2)" v-if="message.type == 'TIMTextElem'">
			<i class="icon icon-business-translate"></i>
			<text class="opr-text">{{ $t('chat.ru')}}→{{ $t('chat.chinese')}}</text>
		</view>
		<view class="item-box" @click.stop="Translate(4)" v-if="message.type == 'TIMTextElem'">
			<i class="icon icon-business-translate"></i>
			<text class="opr-text">{{ $t('chat.chinese') }}→{{ $t('chat.ru') }}</text>
		</view>
		<!-- <view v-if="message.type === types.MSG_FILE || item.type === types.MSG_VIDEO || item.type === types.MSG_IMAGE"
 		@click="openMessage(item)">打开</view>-->
	</view>
</template>

<script lang="ts">
	import {
		JsxEmit
	} from 'typescript';
	import {
		defineComponent,
		watchEffect,
		reactive,
		toRefs,
		getCurrentInstance
	} from 'vue';
	import {
		useI18n
	} from "vue-i18n";
	import store from "../../../../TUICore/store";
	import timStorage from "../../../../utils/tim-storage.js";
	const MessageOperate = defineComponent({
		props: {
			data: {
				type: Object,
				default: () => {
					return {};
				}
			},
			msgid: {
				type: Object,
				default: () => {
					return {};
				}
			},
		},
		setup(props: any, ctx: any) {
			const timStore = store.state.timStore;
			const that = getCurrentInstance();
			const TUIServer: any = uni.$TUIKit.TUIChatServer;
			const {
				t
			} = useI18n();
			const data = reactive({
				message: {},
				dicttext: [],
				token: '',
				id: 0,
				number: 0,
				isFloat: 0,
				audiourl: '',
				adioSize: 0,
				adioFileData: '',
				audiotext: [],
			});
			watchEffect(() => {
				data.message = props.data;
				data.number = props.msgid;
			});
			const dict_text = (e) => {
				data.dicttext = e
				ctx.emit('dict_text', e);
			};
			const voicetext = (e) => {
				ctx.emit('voicetext', e);
			};
			const tran_slate = (e) => {
				data.id = e
				ctx.emit('tran_slate', e);
			};
			//消息回复功能
			const handleReply = () => {
				console.log('触发展示原数据体')
				ctx.emit('reply', true);
			};
			// 处理消息
			const hideTranslate = () => {
				tran_slate(0)
			};
			const handleMessage = async (type: string) => {
				switch (type) {
					case 'copy':
						uni.setClipboardData({
							data: data.message.payload.text,
							success: function() {
								uni.showToast({
									title: t('chat.chat_copy_success'),
									icon: 'none',
								})
							}
						})
						data.dialogID = '';
						break;
					case 'revoke':
						console.log("data.message", data.message)
						await TUIServer.revokeMessage(data.message).then((res) => {
							data.message.isRevoked = true;
							timStorage.update(timStore.messageList[0].id, data.message);
							operateMessage({
								conversation_id: data.message.conversationID,
								message_id: data.message.ID,
								is_revoke: 1
							});
						}).catch((error) => {
							
							uni.showToast({
								title: 'revokeMessage error:' + error.message,
								icon: 'none',
							})
							
						})
						data.dialogID = '';
						break;
					case 'delete':
						console.log("data.message", data.message)
						await TUIServer.deleteMessage([data.message]).then((res) => {
							
							data.message.isDeleted = true;
							timStorage.update(timStore.messageList[0].id, data.message);
							operateMessage({
								conversation_id: data.message.conversationID,
								message_id: data.message.ID,
								is_delete: 1
							});
						}).catch((error) => {
							
							data.message.isDeleted = true;
							timStorage.update(timStore.messageList[0].id, data.message);
							operateMessage({
								conversation_id: data.message.conversationID,
								message_id: data.message.ID,
								is_delete: 1
							});
						});
						data.dialogID = '';
						break;
					case 'forward':
						if (data.message.type === 'TIMImageElem') {
							imageForward()
						}
						if (data.message.type === 'TIMVideoFileElem') {
							videoForward()
						}
						if (data.message.type === 'TIMFileElem') {
							fileForward()
						}
						console.log('cescecssssssssssssssssssssssssssssssssssssssss', JSON.stringify(data
							.message))
						var msUrl = JSON.stringify(data.message).replace(/\&/g, "%26");
						var params = {
							title: "选择好友或群",
							messages: msUrl,
							type: 0
						};
						that.proxy.$goPage('/note/transmit', params);
						data.dialogID = '';
						break;
					case 'resend':
						await TUIServer.resendMessage(data.message);
						data.dialogID = '';
						break;
				}
			};
			const imageForward = () => {
				var imgUrl = data.message.payload.imageInfoArray[0].imageUrl
				imgUrl = imgUrl.replace('?imageMogr2/', '')
				uni.downloadFile({
					url: imgUrl,
					success: (res) => {
						if (res.statusCode === 200) {
							uni.saveFile({
								tempFilePath: res.tempFilePath,
								success: function(result) {
									store.commit("timStore/setImagepath", result
										.savedFilePath)
									console.log("下载好了", JSON.stringify(timStore
										.imagepath))
								},
							})
						}
					}
				})
			};
			const fileForward = () => {
				uni.downloadFile({
					url: data.message.payload.fileUrl,
					success: (res) => {
						if (res.statusCode === 200) {
							uni.saveFile({
								tempFilePath: res.tempFilePath,
								success: function(result) {
									store.commit("timStore/setFilepath", result
										.savedFilePath)
									console.log("下载好了", JSON.stringify(timStore
										.filepath))
								},
							})
						}
					}
				})
			};
			const videoForward = () => {
				uni.downloadFile({
					url: data.message.payload.remoteVideoUrl,
					success: (res) => {
						if (res.statusCode === 200) {
							uni.saveFile({
								tempFilePath: res.tempFilePath,
								success: function(result) {
									store.commit("timStore/setVideopath", result
										.savedFilePath)
									console.log("下载好了", JSON.stringify(timStore
										.videopath))
								},
							})
						}
					}
				})
			}
			const Forward = (e) => {
				data.isFloat = e;
				ctx.emit('Forward', e);
			};
			const For_ward = () => {
				data.isFloat = 1;
				Forward(data.isFloat)
			};
			async function Voicetotext() {
				Downloadvoice().then(() => {
					Transcoding().then(() => {
						var url = JSON.stringify(data.adioFileData)
						url = url.replace(/\\n/g, '')
						url = url.replace(/\\r/g, '')
						var urlSpeech = JSON.parse(url)
						uni.request({
							url: 'https://vop.baidu.com/pro_api', //仅为示例，并非真实接口地址。
							data: JSON.stringify({
								format: "m4a",
								rate: 16000,
								channel: 1,
								token: timStore.baiduyuyinId,
								dev_pid: 80001,
								cuid: " ",
								speech: urlSpeech,
								len: data.adioSize
							}),
							header: {
								'Content-Type': 'application/json;charset=utf-8' //'Content-Type':'audio/pcm;rate=16000' //自定义请求头信息
							},
							method: 'POST',
							success: (res) => {
								data.audiotext[0] = res.data.result[0]
								data.audiotext[1] = data.message['ID']
								store.commit("timStore/setVoicebody", data
									.audiotext)
							}
						})
					})
				})
			};

			function Downloadvoice() {
				return new Promise(resolve => {
					uni.downloadFile({
						url: data.message.payload.remoteAudioUrl,
						success: (res) => {
							if (res.statusCode === 200) {
								uni.saveFile({
									tempFilePath: res.tempFilePath,
									success: function(result) {
										data.audiourl = result.savedFilePath
										resolve()
									},
								})
							}
						}
					})
				})
			}

			function Transcoding() {
				return new Promise(resolve => {
					plus.io.resolveLocalFileSystemURL(data.audiourl, function(entry) {
						entry.file(function(file) {
							var reader = new plus.io.FileReader();
							data.adioSize = file.size;
							console.log('文件大小是。。。。。。。', JSON.stringify(data.adioSize))
							reader.onloadend = function(e) {
								data.adioFileData = e.target.result.split(",")[1];
								// console.log('文件内容是。。。。。。。',data.adioFileData)
								resolve()
							};
							reader.readAsDataURL(file);
						}, function(e) {
							alert(e.message)
							// mui.toast(&#34;读写出现异常: &#34; &#43; e.message);
						})
					})
				})
			}
			
			function operateMessage(param) {
				
				that.proxy.$http.post('/mgr/user/chat/message/operate', param).then((res) => {
					
				}).catch(err => {})
			}
			
			const Translate = (ids) => {
				var fromLang = ''
				var toLang = ''
				switch (ids) {
					case 1:
						fromLang = 'en'
						toLang = 'zh'
						break;
					case 2:
						fromLang = 'ru'
						toLang = 'zh'
						break;
					case 3:
						fromLang = 'zh'
						toLang = 'en'
						break;
					case 4:
						fromLang = 'zh'
						toLang = 'ru'
						break;
					default:
						break;
				}

				var postData = {
					q: data.message.payload.text, //翻译内容
					from: fromLang,
					to: toLang, //中文
				}
				// data.token =store.state.timStore.baidufnayiId
				// console.log('====================================================='+JSON.stringify(timStore))
				//调用百度机器翻译接口
				uni.request({
					url: 'https://aip.baidubce.com/rpc/2.0/mt/texttrans/v1?access_token=' + timStore
						.baidufanyiId, //仅为示例，并非真实接口地址。
					data: postData,
					header: {
						'Content-Type': 'application/json;charset=utf-8' //'Content-Type':'audio/pcm;rate=16000' //自定义请求头信息
					},
					method: 'POST',
					success: (res) => {
						var mgs = data.message['ID']
						// that.dicttext[mgs] = res.data.result.trans_result[0].dst
						// that.dicttext[mgs] = "";
						var valarr = res.data['result']['trans_result']
						data.dicttext[mgs] = ''
						if (valarr.length > 0) {
							for (var i = 0; i < valarr.length; i++) {
								if (i == 0) {
									data.dicttext[mgs] = valarr[i]['dst'] + "\r\n"

								} else {
									data.dicttext[mgs] += valarr[i]['dst'] + "\r\n"
								}
							}
						}
						tran_slate(data.message['ID'])
						dict_text(data.dicttext[mgs])
						//console.log(that.dicttext[mgs]+ "----翻译识别结果");
						//this.resContent = res.data.result.trans_result[0].dst;
						//that.messageSelector.messages[0].payload.text =  that.messageSelector.messages[0].payload.text + res.data.result.trans_result[0].dst
						// that.dataTranslate=res.data.result.trans_result[0].dst;
						//console.log(that.messageSelector.messages[0].payload.text + "----翻译结果");
						//console.log(JSON.stringify(that.messageSelector.messages[0]) + "翻译识别结果");
					}
				})
			};
			return {
				...toRefs(data),
				handleMessage,
				Translate,
				dict_text,
				tran_slate,
				hideTranslate,
				For_ward,
				Voicetotext,
				handleReply
			};
		}
	});
	export default MessageOperate;
</script>
<style lang="scss" scoped>
	.opt-item {
		width: 23%;
		height: 110rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		font-size: 26rpx;
		color: #fff;

		.opt-item-text {
			color: #bec0c0;
		}
	}

	.dialog-container1 {
		display: flex;
		padding: 10rpx 0px 14px;
		width: 270px;
		flex-wrap: wrap;
		background-color: rgba(59, 59, 59, 0.9) !important;
		border-radius: 10rpx;
	}

	.item-box {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-top: 20rpx;
		width: 19%;
		font-family: PingFangSC-Regular;
		font-size: 26rpx;
		font-weight: 400;
		color: #4F4F4F;

		.icon {
			color: #fff;
			font-size: 36rpx;
		}

		.opr-text {
			color: #fff;
			font-size: 24rpx;
		}
	}

	.item-icon {
		flex-shrink: 0;
		display: inline-block;
		width: 22px;
		height: 22px;
		margin-bottom: 5px;
	}
</style>
